<?php
	class Email extends Model_Abstract{
		
		public function addSentEmail($sender, $sendfrom, $subject, $sendto, $content='', $priority=0, $tag=''){
			$sql = "insert into emails set sender=?, sendfrom=?, subject=?, sendto=?, content=?, email_type=?, created=?, priority=?";
			try{
				return $this->_connection->execute($sql,array($sender, $sendfrom, $subject, $sendto, $content, $tag, time(), $priority), true);
			}catch (Exception $e){
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}
		}
		
		public function addSettedCreatedSentEmail($created, $sender, $sendfrom, $subject, $sendto, $content='', $priority=0, $tag=''){
			$sql = "insert into emails set sender=?, sendfrom=?, subject=?, sendto=?, content=?, email_type=?, created=?, priority=?";
			try{
				return $this->_connection->execute($sql,array($sender, $sendfrom, $subject, $sendto, $content, $tag, $created, $priority), true);
			}catch (Exception $e){
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}
		}
		
		public function addShareSentEmail($sender, $sendfrom, $subject, $sendto, $content, $userId, $priority=0){
			$sql = "insert into emails set sender=?, sendfrom=?, subject=?, sendto=?, content=?, user_id=?, email_type=?, created=?, priority=?";
			try{
				return $this->_connection->execute($sql,array($sender, $sendfrom, $subject, $sendto, $content, $userId, 'share', time(), $priority));
			}catch (Exception $e){
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}
		}
		
		public function updateEmailOpenTime($senderto, $uid) {
			$sql = "update emails set open_time=? where user_id=? and email_type='share' and sendto=?";
			try{
				return $this->_connection->execute($sql,array(time(), $uid, $senderto));
			}catch (Exception $e){
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}
		}
		
		public function updateEmailContentById ($id, $content) {
			$sql = "UPDATE emails SET content=? WHERE id=?";
			try{
				return $this->_connection->execute($sql,array($content, $id));
			}catch (Exception $e){
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}
		}
		
		public function addEmailEvent($eventName = '', $logic = '', $conditionArr = array(), $templateId = '')
		{
			try{
				$sql = " INSERT INTO email_events SET event_name=?, logic=?, template_id=?, created=? ";
				if($this->_connection->execute($sql, array($eventName, $logic, $templateId, time()))){
					$eventId = $this->_connection->getLastInsert();
					
					if(!empty($conditionArr)){
						foreach($conditionArr as $contidion => $v){
							$query[] = " (?, ?, ?, ?) ";
							
							$vars[] = $eventId;
							$vars[] = $v['factor'];
							$vars[] = $v['relation'];
							$vars[] = $v['val'];
						}
						
						$sql = " INSERT INTO email_condition(event_id, factor, relation, val) ";
						if(!empty($query)){
							$sql .= ' VALUES ' . implode(' , ', $query);
						}
						if(!$this->_connection->execute($sql, $vars)){
							return false;
						}
					}
					
					if($eventId){
						return array(
							'event_id' => $eventId,
							'event_name' => $eventName,
							'logic' => $logic,
							'conditions' => $conditionArr,
							'conditionsStr' => self::conditionArrToStr($conditionArr, $logic),
							'template_id' => $templateId
						);
					}else{
						return false;
					}
				}
			}catch (Exception $e){
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}
		}
		
		public function modifyEmailEvent($modifyId = '', $eventName = '', $logic = '', $conditionArr = array(), $templateId = '')
		{
			try{
				$sql = " DELETE FROM email_condition WHERE event_id=? ";
				$this->_connection->execute($sql, array($modifyId));
				
				if(!empty($conditionArr)){
					foreach($conditionArr as $contidion => $v){
						$query[] = " (?, ?, ?, ?) ";
						
						$vars[] = $modifyId;
						$vars[] = $v['factor'];
						$vars[] = $v['relation'];
						$vars[] = $v['val'];
					}
					
					$sql = " INSERT INTO email_condition(event_id, factor, relation, val) ";
					if(!empty($query)){
						$sql .= ' VALUES ' . implode(' , ', $query);
					}
					$this->_connection->execute($sql, $vars);
				}
				
				$sql = " UPDATE email_events SET event_name=?, logic=?, template_id=? WHERE id=? ";
				if($this->_connection->execute($sql, array($eventName, $logic, $templateId, $modifyId))){
					return array(
						'event_id' => $modifyId,
						'event_name' => $eventName,
						'logic' => $logic,
						'conditions' => $conditionArr,
						'conditionsStr' => self::conditionArrToStr($conditionArr, $logic),
						'template_id' => $templateId
					);
				}else{
					return false;
				}
				
			}catch (Exception $e){
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}
		}
		
		public function getEmailEvents()
		{
			try{
				$sql = " SELECT e.id, e.event_name, e.logic, e.actived, t.template_name, c.factor, c.relation, c.val FROM email_events e LEFT JOIN email_templates t ON e.template_id=t.id LEFT JOIN email_condition c ON e.id=c.event_id ";
				$result = $this->_connection->query($sql);
				if(count($result) > 0){
					$eventsInfo = array();
					foreach($result as $k => $eventInfo){
						$eventsInfo[$eventInfo['id']]['event_name'] = $eventInfo['event_name'];
						$eventsInfo[$eventInfo['id']]['logic'] = $eventInfo['logic'];
						$eventsInfo[$eventInfo['id']]['template_name'] = $eventInfo['template_name'];
						$eventsInfo[$eventInfo['id']]['actived'] = $eventInfo['actived'];
						$eventsInfo[$eventInfo['id']]['conditions'][] = array(
							'factor' => $eventInfo['factor'],
							'relation' => $eventInfo['relation'],
							'val' => $eventInfo['val']
						);
					}
					foreach($eventsInfo as $eventId => $eventInfo){
						$eventsInfo[$eventId]['conditionsStr'] = self::conditionArrToStr($eventInfo['conditions'], $eventInfo['logic']);
					}
					return $eventsInfo;
				}
				return false;
			}catch (Exception $e){
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}			
		}
		
		public function getImplementEmailEvents()
		{
			try{
				$sql = " SELECT * FROM email_events WHERE actived=1 ";
				return $this->_connection->query($sql);
			}catch (Exception $e){
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}			
		}
		
		public function getEmailEventInfoById($eventId)
		{
			try{
				$sql = " SELECT * FROM email_events e LEFT JOIN email_condition c ON e.id=c.event_id WHERE e.id=? ";
				$result = $this->_connection->query($sql, array($eventId));
				if(count($result) > 0){
					$eventInfo = array(
						'id' => $result[0]['id'],
						'event_name' => $result[0]['event_name'],
						'logic' => $result[0]['logic'],
						'template_id' => $result[0]['template_id']
					);
					foreach($result as $k => $v){
						$eventInfo['conditions'][] = array(
							'factor' => $v['factor'],
							'relation' => $v['relation'],
							'val' => $v['val'],
						);
					}
					
					return $eventInfo;
				}
				
				return false;
			}catch (Exception $e){
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}			
		}
		
		public function deleteEmailEventById($eventId)
		{
			try{
				$sql = " DELETE FROM email_events WHERE id=?;  DELETE FROM email_condition WHERE event_id=? ";
				return $this->_connection->execute($sql, array($eventId, $eventId));
			}catch (Exception $e){
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}			
		}
		
		public function setEmailActived($activeArr)
		{
			try{
				if(!empty($activeArr)){
					foreach($activeArr as $k => $v){
						$id = str_replace('event_', '', $k);
						$active = ($v == 'true')? 1 : 0;
						$sql = " UPDATE email_events SET actived=? WHERE id=?";
						$this->_connection->query($sql, array($active, $id));
					}
				}
				
				return true;
			}catch (Exception $e){
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}			
		}
		
		public function addEmailTemplate($templateName = '', $templateSubject = '', $content = '')
		{
			try{
				$sql = " INSERT INTO email_templates SET template_name=?, template_subject=?, content=?, created=? ";
				if($this->_connection->execute($sql, array($templateName, $templateSubject, $content, time()))){
					$templateId = $this->_connection->getLastInsert();
					return $templateId;
				}
			}catch (Exception $e){
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}
		}
		
		public function getEmailTemplates()
		{
			try{
				$sql = " SELECT * FROM email_templates ";
				return $this->_connection->query($sql);
			}catch (Exception $e){
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}			
		}
		
		public function getEmailTemplateInfoById($templateId)
		{
			try{
				$sql = " SELECT * FROM email_templates WHERE id=? ";
				$result = $this->_connection->query($sql, array($templateId));
				if(count($result) > 0){
					return $result[0];
				}
				
				return false;
			}catch (Exception $e){
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}			
		}
		
		public function deleteEmailTemplateById($templateId)
		{
			try{
				$sql = " DELETE FROM email_templates WHERE id=? ";
				if($this->_connection->execute($sql, array($templateId))){
					$sql = " UPDATE email_events SET template_id=? WHERE template_id=? ";
					return $this->_connection->execute($sql, array(0, $templateId));
				}
				return false;
			}catch (Exception $e){
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}			
		}
		
		public function modifyEmailTemplate($modifyId = '', $templateName = '', $templateSubject, $templateContent = '')
		{
			try{
				$sql = " UPDATE email_templates SET template_name=?, template_subject=?, content=? WHERE id=? ";
				return $this->_connection->execute($sql, array($templateName, $templateSubject, $templateContent, $modifyId));
			}catch (Exception $e){
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}
		}
		
		
		
		private function conditionArrToStr($conditionArr = array(), $logic = 'and')
		{
			$conditions = array();
			$gender = array('Female', 'Male', 'All');
			$sites = DataUtil::getOptionsForSites();
			foreach($conditionArr as $k => $condition){
				$val = $condition['val'];
				if($condition['factor'] == 'site'){
					$val = $sites[$val];
				}
				if($condition['factor'] == 'gender'){
					$val = $gender[$val];
				}
				$conditions[] =  "({$condition['factor']}{$condition['relation']}{$val})";
			}
			
			return implode($logic, $conditions);
		}
		
	}